package io.github.flylinran.modules.app.service;

import io.github.flylinran.common.utils.ShortenUtil;
import io.github.flylinran.modules.app.dao.UrlDao;
import io.github.flylinran.modules.app.entity.UrlEntity;
import io.github.flylinran.modules.app.vo.request.ShortenQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class ShortenService {

    private final UrlDao urlDao;

    public ShortenService(UrlDao urlDao) {
        this.urlDao = urlDao;
    }

    @Transactional
    public Optional<String> shorten(ShortenQuery query) {
        UrlEntity urlEntity = urlDao.save(new UrlEntity().setUrl(query.getUrl()));
        if (urlEntity != null) {
            urlEntity.setCode(ShortenUtil.encode(urlEntity.getId()));
            urlDao.save(urlEntity);
            return Optional.of(urlEntity.getCode());
        }
        return Optional.empty();
    }

    public Optional<String> findUrl(String code) {
        int id = ShortenUtil.decode(code);
        UrlEntity byCode = urlDao.findOne(id);
        return null != byCode ? Optional.of(byCode.getUrl()) : Optional.empty();
    }
}
